﻿using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace SIIMWeb.YIBAO
{

    public class DataUtil
    {
        /// <summary>
        /// 将词典转换成JSON对象
        /// </summary>
        /// <param name="dict"></param>
        /// <returns></returns>
        public static string GetJSON(Dictionary<string, object> dict)
        {
            string json = "{";

            foreach (var item in dict)
            {
                json += string.Format("'{0}':'{1}',", item.Key.ToLower(), item.Value);
            }
            return json.TrimEnd(',') + "}";
        }


        public static T GetObject<T>(string xml)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                byte[] bytes = Encoding.Default.GetBytes(xml);
                ms.Write(bytes, 0, bytes.Length);
                ms.Flush();
                ms.Position = 0;
                XmlSerializer xs = new XmlSerializer(typeof(T));
                return (T)xs.Deserialize(ms);
            }
        }

        public static string GetXml(object spin)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                var xmlSerializerNamespaces = new XmlSerializerNamespaces();
                xmlSerializerNamespaces.Add("", "");
                new XmlSerializer(spin.GetType()).Serialize(new XmlTextWriter(ms, Encoding.UTF8), spin, xmlSerializerNamespaces);
                ms.Flush();
                ms.Position = 0;
                using (StreamReader sr = new StreamReader(ms))
                {
                    return sr.ReadToEnd();
                }
            }
        }
    }
}